precision mediump float;

uniform sampler2D uTilesheet, uMinimap;
uniform float uTileSpace, uTileMargin;
uniform vec2 uTilesheetSize, uTileSize, uWinSize;
varying vec2 vTextureCoord, vOffset;

vec2 getCoord(vec4 color) {
    vec2 coord = color.rg * (uTileSize + uTileSpace) + uTileMargin;
    return (coord + mod(vOffset, uTileSize)) / uTilesheetSize;
}

void main() {
    if (gl_FragCoord.x > uWinSize.x || gl_FragCoord.x < .0 ||
        gl_FragCoord.y > uWinSize.y || gl_FragCoord.y < .0) discard;

    vec4 color = texture2D(uMinimap, vTextureCoord) * 255.0;
    if (color.a == .0) discard;
    vec2 coord = getCoord(color);
    gl_FragColor = texture2D(uTilesheet, coord);
}
